package com.glowdayz.glowmee;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.PorterDuff;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.ContextThemeWrapper;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.view.animation.AnimationUtils;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RatingBar;
import android.widget.TextView;
import android.widget.ViewFlipper;

import com.glowdayz.common.ActivityManager;
import com.glowdayz.common.ImageDownloader;
import com.glowdayz.common.PatternChecker;
import com.glowdayz.common.XmlParser;
import com.glowdayz.model.BrandBannerCMD;
import com.glowdayz.model.BrandCMD;
import com.glowdayz.model.ProductCMD;

public class ListBrandProduct extends Activity implements OnScrollListener, OnItemClickListener {
	
	private ActivityManager am = ActivityManager.getInstance();
	
	ListView listBrandProduct = null;
	
	ArrayList<ProductCMD> list = null;
	DataAdapter adapter = null;
	// Footer 레이아웃
	LinearLayout llFooter = null;
	LinearLayout llHeader = null;
	
	ImageView urlBt = null, facebookBt = null, twiterBt = null, kakaoBt = null, youtubeBt = null, pouchBt = null, eventBt = null;
	
	int paramId = 0;
	String paramTitle = null;
	
	/********** 페이지 구현 **********/
	private int page = 1;						// 현재 페이지
	private final static int pageSize = 20;		// 한 페이지에 보일 수
	private int totalCount = 0;
	
	ViewFlipper flipper = null;
	int bannerTotal = 0;
	int bannerSort = 0;
	// 터치 이벤트 발생 지점의 x좌표 저장
    float xAtDown;
    float xAtUp;
    float yAtDown;
    float yAtUp;
    
    int paramFilter = 0, paramOrder = 0;
	String paramPrice1 = "", paramPrice2 = "", paramCategoryTitle = "";
	
	String pouchUrl = null, url = null, bUrl = null;
	
	LinearLayout bannerText = null;
	ImageView[] indexButtons;
	int currentIndex = 0;
	FrameLayout flipperLayout = null;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_list_brand_product);
		
		am.addActivity(this);
		
		Intent fromIntent = getIntent();
		paramId = fromIntent.getIntExtra("PARAM_id", 0);
		paramTitle = fromIntent.getStringExtra("PARAM_title");
		
		ImageView backBt = (ImageView) findViewById(R.id.backBt);
		backBt.setOnTouchListener(new OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                switch (event.getAction()) {
                    case MotionEvent.ACTION_DOWN: {
                        ImageView view = (ImageView) v;
                        view.getDrawable().setColorFilter(0x77000000,PorterDuff.Mode.SRC_ATOP);
                        view.invalidate();
                        break;
                    }
                    case MotionEvent.ACTION_UP:
                    case MotionEvent.ACTION_CANCEL: {
                        ImageView view = (ImageView) v;
                        view.getDrawable().clearColorFilter();
                        view.invalidate();
                        break;
                    }
                }
                return false;
            }
        });
		backBt.setOnClickListener(new Button.OnClickListener() {
			@Override
			public void onClick(View v) {
				finish();
			}
		});
		
		ImageView okBt = (ImageView) findViewById(R.id.okBt);
		okBt.setImageResource(R.drawable.pick_search);
		okBt.setOnTouchListener(new OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                switch (event.getAction()) {
                    case MotionEvent.ACTION_DOWN: {
                        ImageView view = (ImageView) v;
                        view.getDrawable().setColorFilter(0x77000000,PorterDuff.Mode.SRC_ATOP);
                        view.invalidate();
                        break;
                    }
                    case MotionEvent.ACTION_UP:
                    case MotionEvent.ACTION_CANCEL: {
                        ImageView view = (ImageView) v;
                        view.getDrawable().clearColorFilter();
                        view.invalidate();
                        break;
                    }
                }
                return false;
            }
        });
		okBt.setOnClickListener(new Button.OnClickListener() {
			@Override
			public void onClick(View v) {
				Intent intent = new Intent(ListBrandProduct.this, ProductBrandFilter.class);
				intent.putExtra("PARAM_id", paramId);
				intent.putExtra("PARAM_title", paramTitle);
				
				intent.putExtra("PARAM_order", paramOrder);
				intent.putExtra("PARAM_category", paramCategoryTitle);
				intent.putExtra("PARAM_price1", paramPrice1);
				intent.putExtra("PARAM_price2", paramPrice2);
				
				startActivityForResult(intent, 1);
			}
		});
		
		TextView textTitle = (TextView) findViewById(R.id.textTitle);
		textTitle.setText(paramTitle);
		
		listBrandProduct = (ListView) findViewById(R.id.listBrandProduct);
		listBrandProduct.setSelector(android.R.color.transparent);
		
		LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		llHeader = (LinearLayout) inflater.inflate(R.layout.inc_brand_item, null);
		listBrandProduct.addHeaderView(llHeader);
		
		LayoutInflater li = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		llFooter = (LinearLayout) li.inflate(R.layout.list_footer, null);
		llFooter.setVisibility(View.GONE);
		listBrandProduct.addFooterView(llFooter);
		
		listBrandProduct.setOnScrollListener(this);
        
        list = new ArrayList<ProductCMD>();
		adapter = new DataAdapter(this, list);
		listBrandProduct.setAdapter(adapter);
		listBrandProduct.setOnItemClickListener(this);
		
		if (paramFilter == 0) {
			url = getResources().getString(R.string.server_url) + "/glowmee/listProductXml.do?" +
					"page=" + page + "&count=" + pageSize + "&type=brand&id=" + paramId;
		} else if (paramFilter == 1) {
			url = getResources().getString(R.string.server_url) + "/glowmee/listProductXml.do?" +
					"page=" + page + "&count=" + pageSize + "&type=brand&id=" + paramId +
					"&order=" + paramOrder + "&price1=" + paramPrice1 + "&price2=" + paramPrice2 + "&categoryTitle=" + paramCategoryTitle;
		}
		
		(new ProductListWorker()).execute();
		
		bUrl = getResources().getString(R.string.server_url) + "/glowmee/viewBrandXml.do?id=" + paramId;
		
		(new BrandWorker()).execute();
	}
	
	private void updateIndexes() {
		currentIndex = currentIndex % bannerTotal;
		if (currentIndex < 0) {
			currentIndex = bannerTotal + currentIndex;
		}
		for (int i=0; i<bannerTotal; i++) {
			if (i == currentIndex) {
				indexButtons[i].setImageResource(R.drawable.banner_on);
			} else {
				indexButtons[i].setImageResource(R.drawable.banner_off);
			}
		}
	}
	
	public class DataAdapter extends ArrayAdapter<ProductCMD> {
		private LayoutInflater inflater = null;

		// 생성자. 파라미터에 전달되는 List의 제너릭스 선언에 주의한다.
		public DataAdapter(Context context, List<ProductCMD> objects) {
			super(context, 0, objects);
			inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		}

		// ArrayList에 할당된 각 항목을 하나씩 추출하여 list_item.xml에 표현시키는 메서드
		// 이 메서드는 ListView에 의해서 호출된다.
		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			/** 모든 컴포넌트의 최상위 클래스 */
			View view = null;

			// 데이터를 저장할 View 선언. view 객체는 "list_item.xml"파일을 의미한다.
			if (convertView == null) {
				view = inflater.inflate(R.layout.list_product_item, null);
			} else {
				view = convertView;
			}

			// 하나의 데이터 항목을 추출한다.
			ProductCMD item = getItem(position);

			// 추출한 데이터가 존재한다면 "list_item.xml"안의 컨트롤들을 추출하여 처리한다.
			if (item != null) {
				view.setOnTouchListener(new OnTouchListener() {
					@Override
					public boolean onTouch(View v, MotionEvent arg1) {
						v.setBackgroundResource(android.R.drawable.list_selector_background);
						return false;
					}
				});
				
				ImageView productImg = (ImageView) view.findViewById(R.id.productImg);
				ImageView brandImg = (ImageView) view.findViewById(R.id.brandImg);
				
				TextView productTitle = (TextView) view.findViewById(R.id.productTitle);
				TextView productVolume = (TextView) view.findViewById(R.id.productVolume);
				TextView productPrice = (TextView) view.findViewById(R.id.productPrice);
				TextView productRating = (TextView) view.findViewById(R.id.productRating);
				
				RatingBar productRatingBar = (RatingBar) view.findViewById(R.id.productRatingBar);
				productRatingBar.setFocusable(false);
				productRatingBar.setOnTouchListener(new OnTouchListener() {
					@Override
					public boolean onTouch(View v, MotionEvent event) {
						return true;
					}
				});
				productRatingBar.setStepSize((float) 0.1);
				productRatingBar.setRating(Float.parseFloat(String.valueOf(item.getRatingAvg())));
				
				productTitle.setText(item.getProductTitle());
				productVolume.setText(item.getVolume());
				productPrice.setText(item.getPrice() + "원");
				productRating.setText(String.valueOf(item.getRatingAvg()));
				
				if (item.getCreate_date().equals("null")) {
					productImg.setImageResource(R.drawable.empty_product);
				} else {
					ImageDownloader.getInstance().download(getResources().getString(R.string.server_url) + item.getCreate_date().trim(), productImg);
				}
				
				
				if (item.getImage().equals("null")) {
					brandImg.setImageResource(R.drawable.empty_logo);
				} else {
					ImageDownloader.getInstance().download(getResources().getString(R.string.server_url) + item.getImage().trim(), brandImg);
				}
			}
			return view;
		}
	}
	
	public class ProductListWorker extends AsyncTask<Object, ProductCMD, Object> {
		@Override
		protected void onPreExecute() {
			llFooter.setVisibility(View.VISIBLE);
		}

		@Override
		protected Object doInBackground(Object... params) {
			Object result = null;
			
			XmlPullParser parser = XmlParser.getInstance().getParser(url);
			if (parser == null) {
				this.cancel(true);
				return null;
			}
			
			try {
				String tag = null;
				int type = parser.getEventType();

				/** 읽은 내용을 담기 위한 변수 */
				int idProduct = 0;
				String productTitle = null;
				int idBrand = 0;
				String idBrandValue = null;
				String volume = null;
				int price = 0;
				double ratingAvg = 0.0;
				int rationCount = 0;
				String image = null;
				String productImg = null;
				
				
				// 파싱 처리를 위한 반복 시작
				while (type != XmlPullParser.END_DOCUMENT) {
					// 읽은 태그의 이름
					tag = parser.getName();

					// 현재 읽고 있는 태그의 종류별로 분기
					switch (type) {
					case XmlPullParser.START_TAG:
						/** 원하는 종류의 시작태그를 만났을 때, 값을 추출 */
						if (tag.equals("totalArticleCount")) {
							parser.next();
							totalCount = Integer.parseInt(parser.getText().trim());
						} else if (tag.equals("idProduct")) {
							parser.next();
							idProduct = Integer.parseInt(parser.getText().trim());
						} else if (tag.equals("productTitle")) {
							parser.next();
							productTitle = parser.getText();
						} else if (tag.equals("idBrand")) {
							parser.next();
							idBrand = Integer.parseInt(parser.getText().trim());
						} else if (tag.equals("idBrandValue")) {
							parser.next();
							idBrandValue = parser.getText();
						} else if (tag.equals("volume")) {
							parser.next();
							volume = parser.getText();
						} else if (tag.equals("price")) {
							parser.next();
							price = Integer.parseInt(parser.getText().trim());
						} else if (tag.equals("ratingAvg")) {
							parser.next();
							ratingAvg = Double.parseDouble(parser.getText().trim());
						} else if (tag.equals("rationCount")) {
							parser.next();
							rationCount = Integer.parseInt(parser.getText().trim());
						} else if (tag.equals("brandThumbnail")) {
							parser.next();
							image = parser.getText();
						} else if (tag.equals("productThumbnail")) {
							parser.next();
							productImg = parser.getText();
						}
						
						break;

					case XmlPullParser.END_TAG:
						
						if (tag.equals("item")) {
							ProductCMD item = new ProductCMD(
									idProduct, idBrand, idBrandValue, productTitle, volume, price, ratingAvg, rationCount, image, productImg);
							publishProgress(item);
						}
						break;
					}

					// 다음 태그로 이동하고, 상태값을 변경
					type = parser.next();
				}

			} catch (XmlPullParserException e) {
				System.out.println("파서 생성 실패 >> " + e.toString());
			} catch (IOException e) {
				System.out.println("파서 읽기 실패 >> " + e.toString());
			}
			
			return result;
		}

		@Override
		protected void onProgressUpdate(ProductCMD... param) {
			adapter.add(param[0]);
		}

		@Override
		protected void onPostExecute(Object param) {
			llFooter.setVisibility(View.GONE);
		}
		
		@Override
		protected void onCancelled() {
			llFooter.setVisibility(View.GONE);
			AlertDialog.Builder alert = new AlertDialog.Builder(new ContextThemeWrapper(ListBrandProduct.this, android.R.style.Theme_Holo_Light_Dialog));
			alert.setMessage("일시적인 통신에러입니다.");
			alert.setCancelable(false);
			alert.setPositiveButton("다시 시도", new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					(new ProductListWorker()).execute();
				}
			});
			alert.setNegativeButton("뒤로 가기", new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					finish();
				}
			});
			alert.create();
			alert.show();
		}
	}
	
	public class BrandWorker extends AsyncTask<Object, BrandCMD, Object> {
		@Override
		protected void onPreExecute() {
			llFooter.setVisibility(View.VISIBLE);
		}

		@Override
		protected Object doInBackground(Object... params) {
			Object result = null;
			
			XmlPullParser parser = XmlParser.getInstance().getParser(bUrl);
			if (parser == null) {
				this.cancel(true);
				return null;
			}
			
			try {
				String tag = null;
				int type = parser.getEventType();

				/** 읽은 내용을 담기 위한 변수 */
				int idBrand = 0;
				String brandTitle = null;
				String brandUrl = null;
				String brandFacebook = null;
				String twitter = null;
				String kakaotalk = null;
				String youTube = null;
				int pouchCount = 0;
				int eventCount = 0;
				String thumbnail = null;
				ArrayList<BrandBannerCMD> banner_list = null;
				int idBrandBanner = 0;
				int bannerLinkType = 0;
				String bannerLinkCode = null;
				String banner_thumbnail = null;
				
				// 파싱 처리를 위한 반복 시작
				while (type != XmlPullParser.END_DOCUMENT) {
					// 읽은 태그의 이름
					tag = parser.getName();

					// 현재 읽고 있는 태그의 종류별로 분기
					switch (type) {
					case XmlPullParser.START_TAG:
						/** 원하는 종류의 시작태그를 만났을 때, 값을 추출 */
						if (tag.equals("idBrand")) {
							parser.next();
							idBrand = Integer.parseInt(parser.getText().trim());
						} else if (tag.equals("brandTitle")) {
							parser.next();
							brandTitle = parser.getText();
						} else if (tag.equals("brandUrl")) {
							parser.next();
							brandUrl = parser.getText();
						} else if (tag.equals("brandFacebook")) {
							parser.next();
							brandFacebook = parser.getText();
						} else if (tag.equals("twitter")) {
							parser.next();
							twitter = parser.getText();
						} else if (tag.equals("kakaotalk")) {
							parser.next();
							kakaotalk = parser.getText();
						} else if (tag.equals("youTube")) {
							parser.next();
							youTube = parser.getText();
						} else if (tag.equals("pouchCount")) {
							parser.next();
							pouchCount = Integer.parseInt(parser.getText().trim());
						} else if (tag.equals("eventCount")) {
							parser.next();
							eventCount = Integer.parseInt(parser.getText().trim());
						} else if (tag.equals("thumbnail")) {
							parser.next();
							thumbnail = parser.getText();
						} else if (tag.equals("idBrandBanner")) {
							parser.next();
							idBrandBanner = Integer.parseInt(parser.getText().trim());
						} else if (tag.equals("bannerLinkType")) {
							parser.next();
							bannerLinkType = Integer.parseInt(parser.getText().trim());
						} else if (tag.equals("bannerLinkCode")) {
							parser.next();
							bannerLinkCode = parser.getText();
						} else if (tag.equals("banner_thumbnail")) {
							parser.next();
							banner_thumbnail = parser.getText();
						}
						
						break;

					case XmlPullParser.END_TAG:
						
						if (tag.equals("banner_item")) {
							if (banner_list == null) {
								banner_list = new ArrayList<BrandBannerCMD>();
							}
							banner_list.add(new BrandBannerCMD(idBrandBanner, bannerLinkType, bannerLinkCode, banner_thumbnail));
						}
						
						if (tag.equals("item")) {
							BrandCMD item = new BrandCMD(
									idBrand, brandTitle, brandUrl, brandFacebook, twitter, kakaotalk, youTube, pouchCount, eventCount, thumbnail, banner_list);
							publishProgress(item);
						}
						break;
					}

					// 다음 태그로 이동하고, 상태값을 변경
					type = parser.next();
				}

			} catch (XmlPullParserException e) {
				System.out.println("파서 생성 실패 >> " + e.toString());
			} catch (IOException e) {
				System.out.println("파서 읽기 실패 >> " + e.toString());
			}
			
			return result;
		}

		@Override
		protected void onProgressUpdate(BrandCMD... param) {
			flipperLayout = (FrameLayout) llHeader.findViewById(R.id.flipperLayout);
			flipper = (ViewFlipper) llHeader.findViewById(R.id.viewFlipper);
			if (param[0].getBanner_list() != null) {
				bannerText = (LinearLayout) llHeader.findViewById(R.id.bannerText);
				flipperLayout.setVisibility(View.VISIBLE);
				flipper.setVisibility(View.VISIBLE);
				ArrayList<BrandBannerCMD> list = param[0].getBanner_list();
				bannerTotal = list.size();
				
				for (int i=0; i<list.size(); i++) {
					BrandBannerCMD cmd = list.get(i);
					LayoutInflater li = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
					View vv = li.inflate(R.layout.list_banner_item, null);
					ImageView bannerImg = (ImageView) vv.findViewById(R.id.bannerImg);
					bannerImg.setScaleType(ImageView.ScaleType.FIT_XY);
					ImageDownloader.getInstance().download(getResources().getString(R.string.server_url) + cmd.getCreate_date().trim(), bannerImg);
					bannerSort++;
					
					flipper.addView(vv);
					final int bannerType = cmd.getBannerLinkType();
					final String bannerUrl = cmd.getBannerLinkCode();
					bannerImg.setOnTouchListener(new OnTouchListener() {
						
						@Override
						public boolean onTouch(View v, MotionEvent event) {
							if(event.getAction() == MotionEvent.ACTION_DOWN) {
								xAtDown = event.getX(); // 터치 시작지점 x좌표 저장			
								yAtDown = event.getY();
							} else if(event.getAction() == MotionEvent.ACTION_UP || event.getAction() == MotionEvent.ACTION_CANCEL) {
								xAtUp = event.getX(); 	// 터치 끝난지점 x좌표 저장
								yAtUp = event.getY();
								
								if (xAtUp < xAtDown && (xAtDown - xAtUp) > 10) {
									// 왼쪽 방향 에니메이션 지정
									flipper.setInAnimation(AnimationUtils.loadAnimation(ListBrandProduct.this, R.anim.push_left_in));
							        flipper.setOutAnimation(AnimationUtils.loadAnimation(ListBrandProduct.this, R.anim.push_left_out));
							        		
							        if (bannerTotal > 1) {
										flipper.showNext();
										currentIndex++;
										updateIndexes();
							        }
								} else if (xAtUp > xAtDown && (xAtUp - xAtDown) > 10) {
									// 오른쪽 방향 에니메이션 지정
									flipper.setInAnimation(AnimationUtils.loadAnimation(ListBrandProduct.this, R.anim.push_right_in));
							        flipper.setOutAnimation(AnimationUtils.loadAnimation(ListBrandProduct.this, R.anim.push_right_out));
							        
							        if (bannerTotal > 1) {
										flipper.showPrevious();
										currentIndex--;
										updateIndexes();
							        }		
								} else if ((yAtUp - yAtDown) < 10 && (yAtUp - yAtDown) > -10) {
									Intent intent = null;
									switch (bannerType) {
									case 13:
										intent = new Intent(Intent.ACTION_VIEW, Uri.parse(bannerUrl));
										startActivity(intent);
										break;
										
									case 14:
										intent = new Intent(ListBrandProduct.this, WebPage.class);
										intent.putExtra("PARAM_bannerUrl", bannerUrl);
										startActivity(intent);
										break;
										
									case 15:
										intent = new Intent(ListBrandProduct.this, AddPouch.class);
										startActivity(intent);
										break;
										
									case 16:
										if (PatternChecker.getInstance().isNum(bannerUrl)) {
											intent = new Intent(ListBrandProduct.this, ViewPouch.class);
											intent.putExtra("PARAM_paramId", Integer.parseInt(bannerUrl));
											startActivity(intent);
										}
										break;
										
									case 17:
										if (PatternChecker.getInstance().isNum(bannerUrl)) {
											intent = new Intent(ListBrandProduct.this, ViewProduct.class);
											intent.putExtra("PARAM_id", Integer.parseInt(bannerUrl));
											startActivity(intent);
										}
										break;
										
									case 18:
										if (PatternChecker.getInstance().isNum(bannerUrl)) {
											intent = new Intent(ListBrandProduct.this, ViewEvent.class);
											intent.putExtra("PARAM_id", Integer.parseInt(bannerUrl));
											startActivity(intent);
										}
										break;
										
									case 19:
										if (PatternChecker.getInstance().isNum(bannerUrl)) {
											intent = new Intent(ListBrandProduct.this, ViewNotice.class);
											intent.putExtra("PARAM_id", Integer.parseInt(bannerUrl));
											startActivity(intent);
										}
										break;
										
									case 20:
										if (PatternChecker.getInstance().isNum(bannerUrl)) {
											intent = new Intent(ListBrandProduct.this, ProfileHome.class);
											intent.putExtra("PARAM_id", Integer.parseInt(bannerUrl));
											startActivity(intent);
										}
										break;
									}
								}
							}
							return true;
						}
					});
				}
				
				if (bannerTotal < 1) {
					flipper.setVisibility(View.GONE);
					flipperLayout.setVisibility(View.GONE);
				}
				
				indexButtons = new ImageView[bannerTotal];
				for (int i = 0; i < bannerTotal; i++) {
					indexButtons[i] = new ImageView(ListBrandProduct.this);
					if (i == currentIndex) {
						indexButtons[i].setImageResource(R.drawable.banner_on);
					} else {
						indexButtons[i].setImageResource(R.drawable.banner_off);
					}

					indexButtons[i].setPadding(10, 10, 10, 10);
					bannerText.addView(indexButtons[i]);
				}
			}
			
			final BrandCMD item = param[0];
			
			urlBt = (ImageView) llHeader.findViewById(R.id.urlBt);
			facebookBt = (ImageView) llHeader.findViewById(R.id.facebookBt);
			twiterBt = (ImageView) llHeader.findViewById(R.id.twiterBt);
			kakaoBt = (ImageView) llHeader.findViewById(R.id.kakaoBt);
			youtubeBt = (ImageView) llHeader.findViewById(R.id.youtubeBt);
			
			pouchBt = (ImageView) llHeader.findViewById(R.id.pouchBt);
			eventBt = (ImageView) llHeader.findViewById(R.id.eventBt);
			
			if (item.getBrandUrl().equals("null")) {
				urlBt.setVisibility(View.GONE);
			} else {
				urlBt.setVisibility(View.VISIBLE);
				urlBt.setOnTouchListener(new OnTouchListener() {
		            @Override
		            public boolean onTouch(View v, MotionEvent event) {
		                switch (event.getAction()) {
		                    case MotionEvent.ACTION_DOWN: {
		                        ImageView view = (ImageView) v;
		                        view.getDrawable().setColorFilter(0x77000000,PorterDuff.Mode.SRC_ATOP);
		                        view.invalidate();
		                        break;
		                    }
		                    case MotionEvent.ACTION_UP:
		                    case MotionEvent.ACTION_CANCEL: {
		                        ImageView view = (ImageView) v;
		                        view.getDrawable().clearColorFilter();
		                        view.invalidate();
		                        break;
		                    }
		                }
		                return false;
		            }
		        });
				urlBt.setOnClickListener(new OnClickListener() {
					@Override
					public void onClick(View v) {
						Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(item.getBrandUrl()));
						startActivity(intent);
					}
				});
			}
			
			if (item.getBrandFacebook().equals("null")) {
				facebookBt.setVisibility(View.GONE);
			} else {
				facebookBt.setVisibility(View.VISIBLE);
				facebookBt.setOnTouchListener(new OnTouchListener() {
		            @Override
		            public boolean onTouch(View v, MotionEvent event) {
		                switch (event.getAction()) {
		                    case MotionEvent.ACTION_DOWN: {
		                        ImageView view = (ImageView) v;
		                        view.getDrawable().setColorFilter(0x77000000,PorterDuff.Mode.SRC_ATOP);
		                        view.invalidate();
		                        break;
		                    }
		                    case MotionEvent.ACTION_UP:
		                    case MotionEvent.ACTION_CANCEL: {
		                        ImageView view = (ImageView) v;
		                        view.getDrawable().clearColorFilter();
		                        view.invalidate();
		                        break;
		                    }
		                }
		                return false;
		            }
		        });
				facebookBt.setOnClickListener(new OnClickListener() {
					@Override
					public void onClick(View v) {
						Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(item.getBrandFacebook()));
						startActivity(intent);
					}
				});
			}
			
			if (item.getTwitter().equals("null")) {
				twiterBt.setVisibility(View.GONE);
				//twiterBt.setAlpha(40);
			} else {
				twiterBt.setVisibility(View.VISIBLE);
				twiterBt.setOnTouchListener(new OnTouchListener() {
		            @Override
		            public boolean onTouch(View v, MotionEvent event) {
		                switch (event.getAction()) {
		                    case MotionEvent.ACTION_DOWN: {
		                        ImageView view = (ImageView) v;
		                        view.getDrawable().setColorFilter(0x77000000,PorterDuff.Mode.SRC_ATOP);
		                        view.invalidate();
		                        break;
		                    }
		                    case MotionEvent.ACTION_UP:
		                    case MotionEvent.ACTION_CANCEL: {
		                        ImageView view = (ImageView) v;
		                        view.getDrawable().clearColorFilter();
		                        view.invalidate();
		                        break;
		                    }
		                }
		                return false;
		            }
		        });
				twiterBt.setOnClickListener(new OnClickListener() {
					@Override
					public void onClick(View v) {
						Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(item.getTwitter()));
						startActivity(intent);
					}
				});
			}
			
			if (item.getKakaotalk().equals("null")) {
				kakaoBt.setVisibility(View.GONE);
			} else {
				kakaoBt.setVisibility(View.VISIBLE);
				kakaoBt.setOnTouchListener(new OnTouchListener() {
		            @Override
		            public boolean onTouch(View v, MotionEvent event) {
		                switch (event.getAction()) {
		                    case MotionEvent.ACTION_DOWN: {
		                        ImageView view = (ImageView) v;
		                        view.getDrawable().setColorFilter(0x77000000,PorterDuff.Mode.SRC_ATOP);
		                        view.invalidate();
		                        break;
		                    }
		                    case MotionEvent.ACTION_UP:
		                    case MotionEvent.ACTION_CANCEL: {
		                        ImageView view = (ImageView) v;
		                        view.getDrawable().clearColorFilter();
		                        view.invalidate();
		                        break;
		                    }
		                }
		                return false;
		            }
		        });
				kakaoBt.setOnClickListener(new OnClickListener() {
					@Override
					public void onClick(View v) {
						Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(item.getKakaotalk()));
						startActivity(intent);
					}
				});
			}
			
			if (item.getYouTube().equals("null")) {
				youtubeBt.setVisibility(View.GONE);
			} else {
				youtubeBt.setVisibility(View.VISIBLE);
				youtubeBt.setOnTouchListener(new OnTouchListener() {
		            @Override
		            public boolean onTouch(View v, MotionEvent event) {
		                switch (event.getAction()) {
		                    case MotionEvent.ACTION_DOWN: {
		                        ImageView view = (ImageView) v;
		                        view.getDrawable().setColorFilter(0x77000000,PorterDuff.Mode.SRC_ATOP);
		                        view.invalidate();
		                        break;
		                    }
		                    case MotionEvent.ACTION_UP:
		                    case MotionEvent.ACTION_CANCEL: {
		                        ImageView view = (ImageView) v;
		                        view.getDrawable().clearColorFilter();
		                        view.invalidate();
		                        break;
		                    }
		                }
		                return false;
		            }
		        });
				youtubeBt.setOnClickListener(new OnClickListener() {
					@Override
					public void onClick(View v) {
						Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(item.getYouTube()));
						startActivity(intent);
					}
				});
			}
			
			if (param[0].getPouchCount() > 0) {
				pouchBt.setVisibility(View.VISIBLE);
				pouchBt.setOnTouchListener(new OnTouchListener() {
		            @Override
		            public boolean onTouch(View v, MotionEvent event) {
		                switch (event.getAction()) {
		                    case MotionEvent.ACTION_DOWN: {
		                        ImageView view = (ImageView) v;
		                        view.getDrawable().setColorFilter(0x77000000,PorterDuff.Mode.SRC_ATOP);
		                        view.invalidate();
		                        break;
		                    }
		                    case MotionEvent.ACTION_UP:
		                    case MotionEvent.ACTION_CANCEL: {
		                        ImageView view = (ImageView) v;
		                        view.getDrawable().clearColorFilter();
		                        view.invalidate();
		                        break;
		                    }
		                }
		                return false;
		            }
		        });
				pouchBt.setOnClickListener(new OnClickListener() {
					@Override
					public void onClick(View v) {
						Intent intent = new Intent(ListBrandProduct.this, BrandPouch.class);
						intent.putExtra("PARAM_paramId", paramId);
						intent.putExtra("PARAM_paramTitle", paramTitle);
						startActivity(intent);
					}
				});
			}
			
			if (param[0].getEventCount() > 0) {
				eventBt.setVisibility(View.VISIBLE);
				eventBt.setOnTouchListener(new OnTouchListener() {
		            @Override
		            public boolean onTouch(View v, MotionEvent event) {
		                switch (event.getAction()) {
		                    case MotionEvent.ACTION_DOWN: {
		                        ImageView view = (ImageView) v;
		                        view.getDrawable().setColorFilter(0x77000000,PorterDuff.Mode.SRC_ATOP);
		                        view.invalidate();
		                        break;
		                    }
		                    case MotionEvent.ACTION_UP:
		                    case MotionEvent.ACTION_CANCEL: {
		                        ImageView view = (ImageView) v;
		                        view.getDrawable().clearColorFilter();
		                        view.invalidate();
		                        break;
		                    }
		                }
		                return false;
		            }
		        });
				eventBt.setOnClickListener(new OnClickListener() {
					@Override
					public void onClick(View v) {
						Intent intent = new Intent(ListBrandProduct.this, BrandEvent.class);
						intent.putExtra("PARAM_paramId", paramId);
						intent.putExtra("PARAM_paramTitle", paramTitle);
						startActivity(intent);
					}
				});
			}
			
		}

		@Override
		protected void onPostExecute(Object param) {
			llFooter.setVisibility(View.GONE);
		}
		
		@Override
		protected void onCancelled() {
			llFooter.setVisibility(View.GONE);
			AlertDialog.Builder alert = new AlertDialog.Builder(new ContextThemeWrapper(ListBrandProduct.this, android.R.style.Theme_Holo_Light_Dialog));
			alert.setMessage("일시적인 통신에러입니다.");
			alert.setCancelable(false);
			alert.setPositiveButton("다시 시도", new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					(new BrandWorker()).execute();
				}
			});
			alert.setNegativeButton("뒤로 가기", new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					finish();
				}
			});
			alert.create();
			alert.show();
		}
	}

	// 화면에 리스트의 마지막 아이템이 보여지는 체크
	boolean lastItemVisibleFlag = false;
	
	@Override
	public void onScroll(AbsListView view, int firstVisibleItem,
			int visibleItemCount, int totalItemCount) {
		lastItemVisibleFlag = (totalItemCount > 0) && (firstVisibleItem + visibleItemCount >= totalItemCount);
	}

	@Override
	public void onScrollStateChanged(AbsListView view, int scrollState) {
		if (scrollState == OnScrollListener.SCROLL_STATE_IDLE && lastItemVisibleFlag) {
			int pageCount = ((totalCount -1) / pageSize) + 1;
			if (pageCount > 0 && page < pageCount) {
				page++;
				if (paramFilter == 0) {
					url = getResources().getString(R.string.server_url) + "/glowmee/listProductXml.do?" +
							"page=" + page + "&count=" + pageSize + "&type=brand&id=" + paramId;
				} else if (paramFilter == 1) {
					url = getResources().getString(R.string.server_url) + "/glowmee/listProductXml.do?" +
							"page=" + page + "&count=" + pageSize + "&type=brand&id=" + paramId +
							"&order=" + paramOrder + "&price1=" + paramPrice1 + "&price2=" + paramPrice2 + "&categoryTitle=" + paramCategoryTitle;
				}
				(new ProductListWorker()).execute();
			}
		}
	}
	
	@Override
	public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
		if (arg2 > 0) {
			ProductCMD select = adapter.getItem(arg2 - 1);
			int id = select.getIdProduct();
			String title = select.getProductTitle();
			Intent intent = new Intent(this, ViewProduct.class);
			intent.putExtra("PARAM_id", id);
			intent.putExtra("PARAM_title", title);
			startActivity(intent);
		}
	}
	
	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (resultCode == Activity.RESULT_OK) {
			paramFilter = data.getIntExtra("PARAM_filter", 0);
			paramOrder = data.getIntExtra("PARAM_order", 0);
			paramPrice1 = data.getStringExtra("PARAM_price1");
			paramPrice2 = data.getStringExtra("PARAM_price2");
			paramCategoryTitle = data.getStringExtra("PARAM_category");
			
			adapter.clear();
			
			if (paramFilter == 0) {
				url = getResources().getString(R.string.server_url) + "/glowmee/listProductXml.do?" +
						"page=" + page + "&count=" + pageSize + "&type=brand&id=" + paramId;
			} else if (paramFilter == 1) {
				url = getResources().getString(R.string.server_url) + "/glowmee/listProductXml.do?" +
						"page=" + page + "&count=" + pageSize + "&type=brand&id=" + paramId +
						"&order=" + paramOrder + "&price1=" + paramPrice1 + "&price2=" + paramPrice2 + "&categoryTitle=" + paramCategoryTitle;
			}
			
			(new ProductListWorker()).execute();
		}
	}
	
    @Override
	protected void onDestroy() {
		super.onDestroy();
		am.removeActivity(this);
	}
	
}
